package com.dw.article.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.article.mapper.mp.ArticleMappingMapper;
import com.dw.model.article.dtos.mapping.AddArticleMappingDTO;
import com.dw.model.article.entitys.ArticleInfo;
import com.dw.model.article.entitys.ArticleMapping;
import com.dw.article.service.ArticleMappingService;
import com.dw.model.article.vos.article.QueryByIdVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章标签分类关系表(ArticleMapping)表服务实现类
 *
 * @author makejava
 * @since 2024-10-08 17:52:32
 */
@Service("articleMappingService")
public class ArticleMappingServiceImpl extends ServiceImpl<ArticleMappingMapper, ArticleMapping> implements ArticleMappingService {

    /**
     * 新增文章分类标签映射关系
     */
    @Override
    public Boolean addMapping(AddArticleMappingDTO addArticleMappingDTO) {
        // 参数拷贝
        ArticleMapping articleMapping = new ArticleMapping();
        BeanUtils.copyProperties(addArticleMappingDTO,articleMapping);
        // 设置id
        long l = IdUtil.getSnowflake().nextId();
        articleMapping.setLeiId(l);
        return save(articleMapping);
    }

    /**
     * 根据文章id查询所有关联的标签与分类信息
     */
    @Override
    public QueryByIdVO queryById(Long articleId) {
        // 根据文章id查询所有关联的标签与分类信息
        List<ArticleMapping> list = lambdaQuery()
                .eq(ArticleMapping::getArticleId, articleId)
                .list();
        // 获取分类和标签id列表
        List<Long> labelIds = list.stream().map(ArticleMapping::getLabelId).distinct().collect(Collectors.toList());
        List<Long> categoryIds = list.stream().map(ArticleMapping::getCategoryId).distinct().collect(Collectors.toList());
        // 构建返回参数
        QueryByIdVO queryByIdVO = new QueryByIdVO();
        queryByIdVO.setCategoryIds(categoryIds);
        queryByIdVO.setLabelIds(labelIds);
        return queryByIdVO;
    }

    /**
     * 根据分类id查询文章列表
     */
    @Override
    public List<Long> queryByCategoryId(Long categoryId) {
        // 查询该分类下的所有文章id
        List<ArticleMapping> list = lambdaQuery()
                .eq(ArticleMapping::getCategoryId, categoryId)
                .list();
        return list.stream().map(ArticleMapping::getArticleId).distinct().collect(Collectors.toList());
    }

}

